#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void fillArray(int** arr, int rows, int cols) {
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            arr[i][j] = rand() % 10 + 1;
        }
    }
}
void addArrayToFile(int** arr, int rows, int cols, const char* filename) {
    FILE* file = fopen(filename, "w");
    if (file == NULL) {
        perror("打开文件失败");
        return;
    }
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            if (j == cols - 1) {
                fprintf(file, "%d", arr[i][j]);
            }
            else {
                fprintf(file, "%d,", arr[i][j]);
            }
        }
        fprintf(file, "\n"); // 行末换行
    }
    fclose(file);
}

void readArrayFromFileAndPrint(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (file == NULL) {
        perror("打开文件失败");
        return;
    }

    char buffer[100];
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("%s", buffer); // 打印每一行内容
    }

    fclose(file);
}

int main() {
    srand((unsigned)time(0));

    int rows = 5, cols = 5;

    int** arr = new int* [rows];
    for (int i = 0; i < rows; ++i) {
        arr[i] = new int[cols];
    }

    fillArray(arr, rows, cols);

    // 将数组写入文件
    addArrayToFile(arr, rows, cols, "test.txt");

    // 销毁动态空间
    for (int i = 0; i < rows; ++i) {
        delete[] arr[i];
    }
    delete[] arr;

    // 从文件中读取内容并打印到控制台
    printf("从文件中读取的内容：\n");
    readArrayFromFileAndPrint("test.txt");

    return 0;
}
